/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package core.connector.email.http.gde;

import core.connector.ConnectionDetails;
import core.connector.email.http.gmail.HttpConnectorGmail;
import core.util.JGoogleAnalytics;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.methods.PostMethod;

/**
 *
 * @author Vinicius
 */
public class HttpConnectorGde extends HttpConnectorGmail{

    public HttpConnectorGde(ConnectionDetails connectionDetails){
        super(connectionDetails);
        int index;
        if(connectionDetails.getLogin() != null && ((index = connectionDetails.getLogin().trim().indexOf("@gde.ru")) > -1)){
            String login = connectionDetails.getLogin().substring(0,index);
            connectionDetails.setLogin(login);
            this.user = login;
        }
        JGoogleAnalytics.trackAsynchronously("Connector HTTP - GDE.RU-MAIL");
    }

    @Override
    public boolean connect() {
        System.out.println("CONECTANDO...");
        if (user.equals("") || passwd.equals(""))
        {
            throw new IllegalStateException("Cannot connect: user and password not specified.");
        }
        PostMethod post = new PostMethod("http://mail.gde.ru/login.php");
        post.addRequestHeader("Accept:", "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png;q=0.5");
        post.addRequestHeader("Connection", "keep-alive");
        post.addRequestHeader("Accept-Encoding", "gzip, deflate");
        post.addRequestHeader("Referer", "http://mail.gde.ru/login.php");
        post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        post.addParameter("username", user);
        post.addParameter("password", passwd);
        post.addParameter("samlButton", "?????");
        
       int statusCode = -1;
       String resultado;
        try
        {
            post.setFollowRedirects(false);
            statusCode = client.executeMethod(post);
            resultado = getResponseBodyAsString(post);
            Header[] setcookie = post.getResponseHeaders("set-cookie");
            for(Header cok : setcookie)
                buildCookie(cok);
            if (statusCode == -1)
                System.out.println("ERRO");
            if(GetCookie("user") == null || GetCookie("password") == null){
                throw new Exception("Login/Senha incorreto(s)");
            }
        }catch (Exception ex){
            ex.printStackTrace();
            post.releaseConnection();
            return false;
        }
        post.releaseConnection();
        if(resultado != null && !resultado.isEmpty() && resultado.contains("SAMLResponse")){
            return super.acsConnect(resultado,"https://www.google.com/a/gde.ru/ServiceLogin?service=mail");
        }

        return true;

    }

    @Override
    public String getServiceName(){
        return "a/gde.ru";
    }

}
